var layer;
var form;
var table;
var treeSelect;
var treeTable;
var dropdown;
var iconSelected;
var temp_name;

/**	
 * layui 组件引入
 * @returns
 */
layui.use([ 'layer', 'form', 'table', 'jquery' , "treeSelect", "treeTable", "iconSelected", "dropdown"], function() {
	layer = layui.layer;
	form = layui.form;
	table = layui.table;
	treeSelect = layui.treeSelect;
	treeTable = layui.treeTable;
	iconSelected = layui.iconSelected;
	dropdown = layui.dropdown;

	// 加载字典=============================================================================================
    getDictLabel("is_project", "#isProject", "isProject", true);
    getDictLabel("home_state", "#homeState", "homeState", true);
    getDictLabel("use_state", "#state", "state", true);
    getDictLabel("menu_type", "#type", "type", true);

	// 执行一个 table 实例=============================================================================================
    var treeTablParam = treeTable.render({
		elem : '#data_table',
		id : 'data_table',
		url : ctxPath+'sys/menu/selectTreeTable',
		//height:'full-120', // 自动填充可视高度
		page: false,
		toolbar : '#toolberLeft',
		treeColIndex: 1,	// 树形图标显示在第几列
        treeSpid: 0,		// 最上级的父级id
        treeIdName: 'mid',	// id字段的名称
        treePidName: 'parentId',// pid字段的名称
        treeDefaultClose: false,// 是否默认折叠
        treeLinkage: true,		// 父级展开时是否自动展开所有子级
		cols : [[
			{type : 'checkbox', fixed : 'left', hide: true},  
			{field : 'mname', title : '菜单名称', align : 'left', minWidth: '150', hide: setColumnHide("mname")},
			//{field : 'mid', title : 'ID', align : 'center', minWidth: '80', hide: setColumnHide("mid")},
			{field : 'code', title : '编码', align : 'center', minWidth: '80', hide: setColumnHide("code")},
			{field : 'state', title : '状态', align : 'center', minWidth: '80', hide: setColumnHide("state"), toolbar : '#switchRow'},
			{field : 'isProject', title : '权限', align : 'center', minWidth: '80', hide: setColumnHide("isProject"), templet: function (d){return getDictText("is_project",d.isProject)}},
			{field : 'type', title : '类型', align : 'center', minWidth: '100', hide: setColumnHide("type"), templet: function (d){return getDictText("menu_type",d.isProject)}},
			{field : 'url', title : '路由', align : 'center', minWidth: '100', hide: setColumnHide("url")},
			{field : 'iconCls', title : '图标样式', align : 'center', minWidth: '100', hide: setColumnHide("iconCls"),
				templet:function(res){
					return '<i class="'+res.iconCls+'"></i>';
				}
		    },{fixed : isRight(), title : '操作', align : 'center', minWidth: '200', toolbar : '#toolRow'}
		]],
		done: function () {
			$("#serarch_name").val(temp_name);
		}
	});

	// 头部左侧事件=============================================================================================
    table.on('toolbar(data_table)',  function(obj) {
		if (obj.event === 'search') {
			method.laodTreeTabl();
		}else if(obj.event === 'add'){
			openWindowRB('data_form', '菜单添加', '500px', '100%', false, 0, false, false, null, 0.2, false, function(){
				loadTreeMeun(0);// 下拉树形菜单
				initIconSel()
			});
		}else if(obj.event === 'expand'){
			treeTable.expandAll('#data_table');
		}else if(obj.event === 'fold'){
			treeTable.foldAll('#data_table');
		}
	})

	// 函数对象=============================================================================================
	var method = {
    	laodTreeTabl: function(){
			temp_name = $("#serarch_name").val();
			treeTablParam.where = {"mname": temp_name};
			treeTablParam = treeTable.render(treeTablParam);
    	}
    }

	// 监听行工具事件=============================================================================================
	table.on('tool(data_table)', function(obj) {
		var down_this = this;
		var data = obj.data;
		if (obj.event === 'add') {
			openWindowRB('data_form', '菜单添加', '500px', '100%', false, 0, false, false, null, 0.2, false, function(){
				loadTreeMeun(data.mid);
				initIconSel()
			});
		}else if (obj.event === 'all') {
			dropdown.render({
				elem: down_this
				,show: true // 外部事件触发即显示
				,data: [{
					title: '查看', id: 'detail'
				}, {
					title: '编辑', id: 'edit'
				}, {
					title: '删除', id: 'del'
				}, {
					title: '授权角色', id: 'power'
				}]
				,click: function(d, othis){
					if(d.id === 'detail'){
						openWindowRB('data_form', '菜单查看', '500px', '100%', false, 0, false, false, data, 0.2, false, function(res){
							loadTreeMeun(data.parentId);
							initIconSel(res.iconCls)
						});
					} else if(d.id === 'edit'){
						openWindowRB('data_form', '菜单编辑', '500px', '100%', false, 0, false, false, data, 0.2, false, function(res){
							loadTreeMeun(data.parentId);
							initIconSel(res.iconCls)
						});
					} else if(d.id === 'del'){
						deleteRow(table, 'data_table', {'mid':data.mid}, ctxPath+'sys/menu/delete'+"?mid="+data.mid, function(res){
							if (res.success) {
								method.laodTreeTabl();
							}
						});
					}else  if(d.id === 'power'){
						openWindowRB('role_menu_form', '授权角色', '500px', '100%', false, 0, false, false, data, 0.2, false, function(res){
							table.render({
								elem: '#role_menu_table',
								id: 'role_menu_table',
								url:  ctxPath+"sys/menu/selectMenuRole"+'?mid=' + res.mid,
								height:'full-230',
								page: false,
								cols: [[
									{type: 'checkbox', fixed: 'left'},
									{field: 'rname', width: 100, title: '角色名称'},
									{field: 'state', width: 85, title: '状态', templet: function (d){return getDictText("use_state", d.state, 1)}},
									{field: 'type', width: 90, title: '类型'},
									{field: 'remarks', width: 150, title: '备注'}
								]]
								,done:function(result,currPage,count){//数据回调方法
									var data = result.data;
									data.forEach(function(o, i) {
										if(o.rmstate > 0){
											// 没有开启浮动使用这个即可
											// $('div[lay-id="app-from"] .layui-table-body tr[data-index='+i+'] .layui-form-checkbox').click();
											// 开启左浮动使用这个
											$('div[lay-id="role_menu_table"] .layui-table-fixed tr[data-index='+i+'] .layui-form-checkbox').click();
										}
									})
								},
							});
						});
					}
				}
				,align: 'right' //右对齐弹出（v2.6.8 新增）
				,style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
			});
		}
	});

    // 提交角色菜单=============================================================================================
	form.on('submit(roleMenuForm)', function(data) {
		var mid = data.field.mid;
		var check = table.checkStatus('role_menu_table');
	    var rids = [];
	    $(check.data).each(function (i, o) {// o 即为表格中一行的数据
	    	rids.push(o.rid);
	    });
	    var text = sbumitLoading('#role_menu_form .lay-submit-btn');
	    getAjax(ctxPath+"sys/menu/saveMenuRole", {rids: rids.join(","), mid: mid}, 'post', function (res) {
	        if (res.success) {
	            layer.closeAll();
	        }
	        showTips(res.msg);
	        closeLoading('#role_menu_form .lay-submit-btn', text)
	    })
	    return false;
	})

	// 提交=============================================================================================
	form.on('submit(submitForm)', function(data) {
		saveData(table, 'data_table', data.field, ctxPath+'sys/menu/save', '#data_form ', function(res){
			if (res.success) {
				method.laodTreeTabl();
	        }
		});
		return false;
	})

	// 开关=============================================================================================
	form.on('switch(stateSwitch)', function(data) {
		var mid = $(this).attr('mid');
	    var state = data.elem.checked?"1":"0";
	    getAjax(ctxPath+"sys/menu/updateState", {mid: mid, state: state}, 'post', function (res) {
	        showTips(res.msg);
	    })
		return false;
	})



})

/**
 * ---------------------------------------------------------------------------------------------------------------------
 * 初始化图标选择器
 */
function initIconSel(icon){
	$(".layui-ext-icon-selected-input").remove();
	$(".layui-ext-icon-selected-container").remove();
	iconSelected.render("#iconCls", {value: icon});
}


/**
 * ---------------------------------------------------------------------------------------------------------------------
 * 获取所有菜单-树形
 */
function loadTreeMeun(id){
	$.get(ctxPath+"sys/menu/selectTreeAll", {}, function (result) {
		if (result.success){
			treeSelect.destroy('parentTree');
			// 参考：https://wujiawei0926.gitee.io/treeselect/docs/doc.html
			treeSelect.render({
				elem: '#parentTree',
				data:  '',
				list: result.data,
				type: 'get',
				placeholder: '请选择菜单',
				search: true,
				style: {
					folder: {
						enable: false // 图标
					},
					line: {
						enable: true  // 线
					}
				},
				click: function(d){
					console.log(d);
				},
				success: function (d) {
					// 选中节点，根据id筛选
					treeSelect.checkNode('parentTree', id);
					// 刷新树结构
					treeSelect.refresh('parentTree');
				}
			});
		}
	})
}



